import Vue from "vue"
import Vuex from "vuex"
import getters from "./getters"
import {
  getContactGroupList,
  getCurrentChat,
  getCurrentChatInfo,
  getCurrentUserInfo,
  getFriendList
} from "@/api/user"
import lockr, { set } from "lockr"
import { getDeparmentTree, getSettingInfo } from "@/api/common"
import { deleteChat, getRecentChatList } from "@/api/chat"
import { login } from "@/api/auth"
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    mqttAction: {}, //mq信息
    mqStatus: true, // mqtt状态
    groupList: [], //群组列表
    themeColor: "1, 118, 246",
    recentChatList: [],
    recentTopChatList: [],
    departTreeList: [],
    friendList: [],
    // chatId: "33452959624000198",
    chatId: "",
    receiverId: "",
    activeMenu: "badge",
    lastIndex: 0,
    client: null,
    currentChatInfo: {}, //当前聊天窗口信息
    currentChatUserInfo: {}, //当前聊天人的信息
    isGroup: true,
    userInfo: lockr.get("userInfo") || {},
    systemInfo: lockr.get("systemInfo") || {},
    token: lockr.get("token") || "",
    currentChat: {}
  },
  getters,
  mutations: {
    catchMqttAction(state, data) {
      state.mqttAction = data
    },
    setChatId(state, data) {
      state.chatId = data
    },
    setIsGroup(state, data) {
      state.isGroup = data
    },
    setCurrentChatUserInfo(state, data) {
      state.currentChatUserInfo = data
    },
    setReceiverId(state, data) {
      state.receiverId = data
    },
    setCurrentChatInfo(state, data) {
      state.currentChatInfo = data
    },
    setLastIndex(state, data) {
      state.lastIndex = data
    },
    setClient(state, data) {
      state.client = data
    },
    setSelectedMenu(state, data) {
      state.activeMenu = data
    },
    setThemeColor(state, data) {
      let color
      let storeColor = lockr.get("themeColor")
      if (!data) {
        color = storeColor ? storeColor : state.themeColor
      } else {
        color = data
      }
      state.themeColor = color
      lockr.set("themeColor", color)
      const app = document.querySelector("#app")
      const body = document.querySelector("body")
      app.style.setProperty("--color-primary", state.themeColor)
      body.style.setProperty("--color-primary", state.themeColor)
    },
    updateChatList(state, data) {
      const index = state.recentChatList.findIndex(
        (item) =>
          item.receiverId == data.receiverId ||
          (item.receiverId == data.senderId && data.isGroup === false)
      )
      if (index > -1) {
        let {
          unreadCount,
          lastSendTime,
          lastContent,
          lastMessageType,
          senderName,
          ...rest
        } = state.recentChatList[index]
        let updateChat = {
          ...rest,
          unreadCount:
            data.unreadCount !== undefined ? data.unreadCount : unreadCount + 1,
          lastSendTime: data.sendTime,
          lastContent: data.contentText || data.content,
          lastMessageType: data.type,
          lastSenderName: data.senderName,
          type: data.type
        }
        console.log("updateChat", updateChat)
        state.recentChatList.splice(index, 1)
        state.recentChatList.unshift(updateChat)
      }

      const topIndex = state.recentTopChatList.findIndex((item) => {
        return (
          item.receiverId == data.receiverId ||
          (item.receiverId == data.senderId && data.isGroup === false)
        )
      })
      if (topIndex > -1) {
        let { unreadCount, lastSendTime, lastContent, senderName, ...rest } =
          state.recentTopChatList[topIndex]
        let updateChat = {
          ...rest,
          unreadCount:
            data.unreadCount !== undefined ? data.unreadCount : unreadCount + 1,
          lastSendTime: data.sendTime,
          lastContent: data.contentText || data.content,
          senderName: data.senderName,
          lastMessageType: data.type,
          type: data.type
        }
        state.recentTopChatList.splice(topIndex, 1)
        state.recentTopChatList.unshift(updateChat)
      }
    },
    updateActionChat(state, { id, ...rest }) {
      const index = state.recentChatList.findIndex((item) => item.id == id)
      if (index > -1) {
        const updateChat = state.recentChatList[index]
        state.recentChatList.splice(index, 1, { ...updateChat, ...rest })
      }

      const topIndex = state.recentTopChatList.findIndex(
        (item) => item.id == id
      )
      if (topIndex > -1) {
        const updateChat = state.recentTopChatList[topIndex]
        state.recentTopChatList.splice(topIndex, 1, { ...updateChat, ...rest })
      }
    },
    SET_GROUP(state, data) {
      state.groupList = data.map(({ members, ...rest }) => {
        return {
          ...rest,
          members,
          avatarList: members
            .map((item) => {
              return item.avatar ? item.avatar : item.username
            })
            .slice(0, 9)
        }
      })
    },
    SET_RECENT_CHAT_LIST(state, data) {
      state.recentChatList = data
      // state.recentTopChatList = data.filter((item) => item.isTop)
    },
    SET_DEPAR_TREE_LIST(state, data) {
      state.departTreeList = data
    },
    SET_FRIEND_LIST(state, data) {
      state.friendList = data
    },
    setUserInfo(state, data) {
      lockr.set("userInfo", data)
      state.userInfo = data
    },
    setSystemInfo(state, data) {
      state.systemInfo = data
      lockr.set("systemInfo", data)
    },
    setToken(state, data) {
      state.token = data
      lockr.set("token", data)
    },
    setCurrentChat(state, data) {
      state.currentChat = data
    }
  },
  actions: {
    /**
     * 获取当前用户 信息
     * @returns Promise
     */
    getUserInfo({ commit }, val) {
      return new Promise((resolve, reject) => {
        getCurrentUserInfo({ token: val })
          .then(async (res) => {
            const data = res.data
            commit("setUserInfo", {
              ...data,
              userId: data.id,
              userName: data.username
            })
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    getCurrentChatInfo({ commit, state }) {
      console.log(state.groupList)
      const data = state.groupList.find((item) => item.id == state.receiverId)
      if (data) {
        commit("setCurrentChatInfo", data)
      }
    },
    /**
     * 获取当前聊天用户信息
     * @returns Promise
     */
    getCurrentChatUserInfo({ commit }, val) {
      return new Promise((resolve, reject) => {
        getCurrentUserInfo(val)
          .then(async (res) => {
            commit("setCurrentChatUserInfo", res.data)
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    /**
     * 获取群组列表
     * @returns Promise
     */
    getGroupList({ commit, state }) {
      return new Promise((resolve, reject) => {
        getContactGroupList()
          .then((res) => {
            commit("SET_GROUP", res.data)
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    /**
     * 获取会话列表
     * @returns Promise
     */
    getRecentChatList({ commit, state }) {
      return new Promise((resolve, reject) => {
        getRecentChatList({
          filter: {}
        })
          .then((res) => {
            commit("SET_RECENT_CHAT_LIST", res.data)
            const curChat = [
              ...state.recentTopChatList,
              ...state.recentChatList
            ].find((item) => item.id === state.chatId)
            if (curChat) {
              commit("setCurrentChatInfo", curChat)
            }
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    /**
     * 获取系统信息
     * @returns Promise
     */
    async getSystemInfo({ commit }) {
      const { data } = await getSettingInfo()
      commit("setSystemInfo", data)
    },

    /**
     * 获取好友列表
     */
    getFriendList({ commit }) {
      return new Promise((resolve, reject) => {
        getFriendList()
          .then((res) => {
            commit("SET_FRIEND_LIST", res.data)
            resolve(res.data)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    /**
     * 获取部门列表
     * @returns Promise
     */
    getDeparmentTree({ commit }) {
      return new Promise((resolve, reject) => {
        getDeparmentTree({
          filter: {
            // eslint-disable-next-line no-undef
            parentId: departParentId
          }
        })
          .then((res) => {
            commit("SET_DEPAR_TREE_LIST", res.data)
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    async doSubscribe({ commit, dispatch, state }, isSiderChat) {
      // ACTION("im/notice", "通知"), SIMPLE("im/simple", "单聊"), GROUP("im/group", "群聊");
      const friends = await dispatch("getFriendList")
      function getPrivateTopic(uid1, uid2) {
        const [a, b] = [uid1, uid2].sort((x, y) => x - y)
        return `im/simple/${a}_${b}`
      }
      const simpleList = friends.map((item) => getPrivateTopic(item.id))
      const userId = state.userInfo.userId
      const topicList = [
        `im/notice/${userId}`,
        ...simpleList,
        ...state.groupList.map((item) => `im/group/${item.id}`)
      ]
      state.client.subscribe(topicList, { qos: 0 }, (error) => {
        if (error) {
          console.log("订阅主题失败", error)
          return
        }
        console.log("订阅主题成功")
      })
    },
    async doUnSubscribe({ commit, dispatch, state }, id) {
      const curRecentChat = [
        ...state.recentTopChatList,
        ...state.recentChatList
      ].find((item) => item.id === id)
      if (curRecentChat) {
        state.client.unsubscribe(
          `im/group/${curRecentChat.receiverId}`,
          { qos: 0 },
          (error) => {
            if (error) {
              console.log("退订主题失败", error)
              return
            }
            console.log("退订主题成功")
          }
        )
        // if (curRecentChat.id === state.receiverId) {
        //   commit("setReceiverId", "")
        // }
        await dispatch("getRecentChatList")
      }
    },
    async deleteChat({ commit, dispatch, state }, id) {
      const res = await deleteChat(id)
      if (res) {
        dispatch("getRecentChatList")
        dispatch("getGroupList")
        commit("setReceiverId", "")
      }
    },
    login({ commit, dispatch, state }, formData) {
      // const { data } = await login(formData)
      // commit("setUserInfo", data)
      // commit("setToken", data.token)
      return new Promise((resolve, reject) => {
        login(formData)
          .then((res) => {
            commit("setToken", res.data.token)
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
      // await dispatch("doSubscribe", true)
    }
  },
  modules: {}
})
